<template>
  <div class="hello">
    <div class="home">
      <div class="main">
        <div>
          <div class="top">
            <div :class="index == 0 ? 'top-item1' : 'top-item'" v-for="(item, index) in  headerList "
              @click="statusBtn(item.status, index)">
              <div class="test1">
                <div>
                  <i :class="`el-icon-${item.icon}`" :style=item.style></i>
                  <span style="color: #C0C4CC;font-size: 14px;margin-left: 10px;">{{ item.name }}</span>
                </div>
                <div style="color: rgba(24, 144, 255, 1);font-size: 36px;padding-top: 10px;display: flex;" class="test1">
                  <span style="color: #303133;;font-weight: 600;margin: auto;font-size: 18px;">{{ item.count }}</span>
                </div>
              </div>
              <div class="bottomLine" :class="{ selected: selected == index }" style="height: 5px;border-radius: 2px;">
              </div>
            </div>
            <div style="margin-left: 450px; display: flex;margin-right: 24px;">
              <el-button type="primary" @click="newTask" style="margin-left: 30px;" v-if="createFlag">新建任务</el-button>
              <el-button type="primary" @click="openImportTask"
                style="margin-left: 30px;;background: transparent; color: #47ACF4;" v-if="createFlag">批量导入任务</el-button>
              <el-button type="primary" @click="exportExcel"
                style="margin-left: 30px;background: transparent; color: #47ACF4;">导出</el-button>
            </div>
          </div>
        </div>
        <div style="margin: 12px 24px;">
          <!-- <Table :headerCellStyle="headerCellStyle" :columns="columns" :data="tableData" :tableStyle="tableStyle"
            :edit="{ view: true, edit: true, delete: true }" /> -->
          <el-table :data="tableData" :cell-style="tableStyle" :header-cell-style="headerCellStyle" style="width: 100%">
            <el-table-column v-for="(column, index) of columns" :key="index" :prop="column.prop" :label="column.label"
              :fixed="column.fixed" :width="column.width">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="130">
              <template slot-scope="scope">
                <el-button @click="editRow(scope.row)"
                  v-if="adminFlag || (editAndDeleteFlag && scope.row.status == '待审批')" type="text"
                  size="small">编辑</el-button>
                <el-button @click="submitTable(scope.row)" v-if="submitFlag && scope.row.status == '待审批'" type="text"
                  size="small">提交</el-button>
                <el-button @click="approveTable(scope.row)" v-if="approveFlag && scope.row.status == '审批中'" type="text"
                  size="small">审批</el-button>
                <el-button @click="view(scope.row)" v-if="viewFlag && scope.row.status != '待审批'" type="text"
                  size="small">详情</el-button>
                <el-button @click="deleteItem(scope.row)"
                  v-if="adminFlag || (editAndDeleteFlag && scope.row.status == '待审批')" type="text"
                  size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog :visible.sync="approveShow" width="80%">
          <!-- 审批 -->
          <template>
            <div style="margin-top: 50px; width: 97%;">
              <el-form ref="form" :model="opinionform" label-width="100px">
                <el-row style="margin-top: 30px;">
                  <el-col :span="24">
                    <el-form-item label="审批意见：" prop="opinions">
                      <el-input type="textarea" v-model="opinionform.opinions" placeholder="请输入" :rows="4"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="" prop="status">
                      <el-radio-group v-model="opinionform.status">
                        <el-radio :label="'1'">同意</el-radio>
                        <el-radio :label="'2'">不同意</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="审批人：" prop="userId">
                      <el-select ref="userId" :disabled="true" filterable v-model="opinionform.userId" placeholder="请选择"
                        style="width: 100%;">
                        <el-option v-for="  item   in  userList  " :key="item.value" :label="item.name"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="审批时间" prop="time">
                      <el-date-picker :disabled="true" value-format="yyyy-MM-dd HH:mm:ss" v-model="opinionform.time"
                        type="date" style="width: 100%;" placeholder="选择日期时间"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="">
                  <el-button type="primary" @click="approveTask">提交</el-button>
                </el-form-item>
              </el-form>
            </div>
          </template>
        </el-dialog>
        <el-dialog title="批量导入任务" :visible.sync="importFlag">
          <el-form label-width="100px">
            <el-form-item label="相关附件">
              <el-upload :auto-upload="false" action="javascript:void(0)" :on-remove="handleRemove" :file-list="fileList"
                :on-change="handleChange">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
          <div style="text-align: right;">
            <el-button type="primary" style="height: 30px;" @click="downMB">模板下载</el-button>
            <el-button type="primary" style="height: 30px;" @click="importTask">确定导入</el-button>
            <el-button style="height: 30px;" @click="importFlag = false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import Table from '@/components/NormalTable'
import { getTaskList, deleteTask, getAllUser, importTask } from '@/api/project/task'
import { downloadGet } from '@/utils/request'
import { URL } from "/public/config";
export default {
  components: {
    Table,
  },
  props: {

  },
  data() {
    return {
      importFlag: false,
      createFlag: false,
      adminFlag: false,
      viewFlag: false,
      approveFlag: false,
      submitFlag: false,
      editAndDeleteFlag: false,
      opinionform: {},
      approveShow: false,
      userList: [],
      fileList: [],
      headerCellStyle: {
        "background-color": '#F5F7FA',
        'text-align': 'center',
        'font-family': 'PingFangSC-Medium',
        'font-weight': 600,
        'font-size': '14px',
        'color': '#606266',
        'line-height': '22px'
      },
      tableStyle: {
        "text-align": 'center',
      },
      selected: 0,
      formInline: {
        user: '',
        region: ''
      },
      columns: [
        { prop: 'index', label: '序号', width: '', fixed: false },
        { prop: 'name', label: '任务名称', width: '200', fixed: false },
        { prop: 'no', label: '任务编号', width: '140', fixed: false },
        { prop: 'taskTypeName', label: '任务类型', width: '100', fixed: false },
        { prop: 'taskCount', label: '数量', width: '200', fixed: false },
        { prop: 'taskUnit', label: '单位', width: '100', fixed: false },
        { prop: 'nature', label: '任务下达性质', width: '120', fixed: false },
        { prop: 'projectName', label: '项目名称', width: '120', fixed: false },
        { prop: 'releaseTime', label: '开始时间', width: '120', fixed: false },
        { prop: 'endTime', label: '完成时间', width: '100', fixed: false },
        { prop: 'status', label: '状态', width: '120', fixed: false },
        { prop: 'undertakeDeptName', label: '承办部门', width: '120', fixed: false },
        { prop: 'feeTotal', label: '经费下达总额', width: '', fixed: false },
        { prop: 'feeUnitPrice', label: '经费下达单价', width: '', fixed: false },
        { prop: 'overallCompletionRate', label: '进度', width: '', fixed: false },
        { prop: 'taskContent', label: '任务描述', width: '300', fixed: false },
        { prop: 'remark', label: '备注', width: '', fixed: false },
        // { type: 'operation', label: '操作', width: '150px', fixed: "right" },
      ],
      tableData: [],
      headerList: [
        {
          name: '全部项目',
          icon: 'menu',
          count: '20',
          style: 'color:#47ACF4;font-size: 18px;',
        },
        {
          name: '进行中',
          icon: 's-claim',
          count: '18',
          style: 'color:#F9CD43;font-size: 18px;',
        },
        {
          name: '已完成',
          icon: 'document-checked',
          count: '3',
          style: 'color:#2ABF73;;font-size: 18px;font-weight: 600;',
        }
      ],
      userRole: []
    }
  },
  mounted() {
    this.getAllUserListInfo()
    this.userRole = this.$store.state.userInfo.userRoleKeyList
    this.userRole.forEach(item => {
      if (item == 'admin' || item == 'zgb_scgly') {
        this.viewFlag = true
        this.editAndDeleteFlag = true
        this.approveFlag = true
        // this.submitFlag = true
        this.adminFlag = true
        this.createFlag = true
      }
      if (item == 'scbm_fzr') {
        this.viewFlag = true
        this.editAndDeleteFlag = true
        this.submitFlag = true
        this.createFlag = true
      } else {
        this.viewFlag = true
      }
    });
    this.loadTable();
  },
  methods: {
    loadTable() {
      getTaskList({
        projectId: this.$route.query.id
      }).then(res => {
        res.rows.sort(function (a, b) {
          // 将时间字符串转换为日期对象，以便进行比较
          var dateA = new Date(a.releaseTime);
          var dateB = new Date(b.releaseTime);
          return dateA - dateB;
        });
        this.tableData = res.rows;
        this.tableData.forEach((item, index) => {
          item.index = index + 1
          item.nature = this.convertDictValueToLabel(item.nature, 'xmgl_task_nature');
          item.taskUnitName = this.convertDictValueToLabel(item.taskUnit, 'xmgl_task_unit');
          item.taskTypeName = this.convertDictValueToLabel(item.taskType, 'xmgl_task_type');
          item.status = this.convertDictValueToLabel(item.status, 'xmgl_status');
        });
        this.total = res.total
        this.tableData.forEach((tabrow, index) => {
          tabrow.index = index + 1
        });
        this.headerList[0].count = res.total
        this.headerList[1].count = res.status[2] ? res.status[2] : 0;
        this.headerList[2].count = res.status[3] ? res.status[3] : 0;
      });
    },
    view(row) {
      let id = this.tableData[row.index - 1].id
      this.$router.push({
        path: '/taskDetails',
        query: {
          taskId: id
        }
      });
    },
    editRow(row) {
    },
    deleteItem(row) {
      deleteTask(row.id).then(res => {
        if (res.code = 200) {
          alert("删除成功！")
          this.loadTable();
        }
      })
    },
    //审批任务流程
    approveTable(row) {
      this.approveShow = true
      this.rowId = this.tableData[row.index - 1].id
    },
    approveTask() {
      if (this.opinionform.opinions) {
        launchNewTaskApprove(this.rowId, this.opinionform).then(res => {
          if (res.code == 200) {
            alert("审批成功！")
            this.approveShow = false
            this.loadTable()
          }
        })
      } else {
        alert("请填写审批意见")
      }

    },
    statusBtn(status, index) {
      this.selected = index
      this.formInline.status = status
      this.taskSearch()
    },
    exportExcel() {
      downloadGet('task/export', this.formInline, `任务列表.xlsx`)
    },
    //发起任务流程
    submitTable(row) {
      let id = this.tableData[row.index - 1].id
      launchNewTask(id).then(res => {
        if (res.code == 200) {
          alert("提交成功！")
          this.loadTable()
        }
      })
    },
    //查询项目
    taskSearch() {
      if (this.formInline.startTime > this.formInline.endTime) {
        alert("开始时间必须小于结束时间")
        return
      }
      this.formInline.projectId = this.$route.query.id
      this.formInline.orderByColumn = "createTime"
      this.formInline.isAsc = 'desc'
      getTaskList(this.formInline).then(res => {
        this.tableData = res.rows;
        this.tableData.forEach((item, index) => {
          item.index = index + 1
          item.natureName = this.convertDictValueToLabel(item.nature, 'xmgl_task_nature');
          item.taskTypeName = this.convertDictValueToLabel(item.taskType, 'xmgl_task_type');
          item.taskUnitName = this.convertDictValueToLabel(item.taskUnit, 'xmgl_task_unit');
          item.statusName = this.convertDictValueToLabel(item.status, 'xmgl_status');
        });
        this.total = res.total
      });
    },
    newTask() {
      let projectId = this.$route.query.id
      console.log('pro', projectId)
      this.$router.push('/newTask?id=' + projectId);
    },
    // 获取所有用户
    getAllUserListInfo() {
      getAllUser().then(res => {
        this.userList = res.data;
      })
    },
    openImportTask() {
      this.importFlag = true

    },
    downMB() {
      window.open(this.downBaseUrl + '/xmgl/template/%E9%A1%B9%E7%9B%AE%E7%AE%A1%E7%90%86%E4%BB%BB%E5%8A%A1%E4%B8%8B%E8%BE%BE%E5%88%86%E8%A7%A3%E6%A8%A1%E6%9D%BF.xlsx');
    },
    importTask() {
      console.log(this.fileList)
      let formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      importTask(formData).then(res => {
        this.$modal.msgSuccess("导入成功！");
        this.importFlag = false
        console.log(res)
      })

    },
    //附件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 材料改变
    handleChange(file, fileList) {

      const res = this.beforeAvatarUpload(file, fileList);
      if (!res || fileList.length >= 2) {
        fileList.shift();
      }
      this.fileList = fileList;
    },
    // 上传前控制
    beforeAvatarUpload(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过100MB!`);
      }
      return isLt2M;
    },
    // 定义一个函数用于转换字典值为标签
    convertDictValueToLabel(dictValue, dictName) {
      const labelMap = {};
      let dict = this.$store.state.dictNew[dictName]
      dict.forEach(item => {
        labelMap[item.value] = item.label
      });
      let label = '';
      if (labelMap.hasOwnProperty(dictValue)) {
        label += labelMap[dictValue] + ' ';
      }
      // console.log('label', label.trim())
      return label.trim(); // 去除首尾空格
    },
  }
}
</script>

<style scoped lang="scss">
.home {
  display: flex;
  flex-direction: column;
  width: 100wh;
  /* height: 100vh; */
  padding: 0px;
  /* background-color: aqua; */
  background-color: #F5f7fa;
  font-weight: 500;

  .top {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    text-align: center;
    align-items: center;
    width: 100wh;
    height: 12vh;
    padding: 0px;
    /* background-color: rgb(0, 255, 55); */

    .top-item1 {
      display: flex;
      flex-direction: column;
      margin-left: 15px;
      padding-left: 15px;
      // border-left: 2px solid #DCDFE6;
    }

    .top-item {
      display: flex;
      flex-direction: column;
      margin-left: 15px;
      padding-left: 15px;
      border-left: 2px solid #DCDFE6;

      .greenPoint {
        background-color: #2ABF73;
        height: 10px;
        width: 10px;
        margin-right: 5px;
        margin-top: 19px;
        border-radius: 5px;
        margin-left: 10px;
      }
    }

    .test1:hover+.bottomLine {
      background-color: #DCDFE6;
    }

    .selected {
      background-color: skyblue;
    }

  }

  .search {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #FFFFFF;
    margin-top: 20px;
  }

  .main {
    // margin-top: 10px;
    background-color: #FFFFFF;
  }
}
</style>
